package db

import (
	"fmt"
	"gorm.io/gorm/logger"
	"server/libs/log"
	"time"

	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var mysqlDB *gorm.DB

type DBWriter struct {
	m_log *logrus.Logger
}

func (m *DBWriter) Printf(format string, v ...interface{}) {
	logstr := fmt.Sprintf(format, v...)
	log.Logs().Info(logstr)
}
func NewMyWriter() *DBWriter {
	return &DBWriter{m_log: log.Logs()}
}
func InitMysql(host string) {
	var err error
	slowLogger := logger.New(
		NewMyWriter(),
		logger.Config{
			SlowThreshold: time.Millisecond,
			LogLevel:      logger.Info,
		},
	)
	mysqlDB, err = gorm.Open(mysql.Open(host), &gorm.Config{
		Logger: slowLogger,
	})
	if err != nil {
		log.Logrus().WithFields(logrus.Fields{}).Panic("数据库链接错误")
	}
	sqlDB, _ := mysqlDB.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(59 * time.Second)
}

func Mysql() *gorm.DB {
	return mysqlDB
}
